package cc.rengu.igas.share.core.service.channel.cpcn;

import cc.rengu.igas.channel.cpcn.facade.base.Header;
import cc.rengu.igas.channel.cpcn.facade.request.CpcnMchntOrderPayRefundQueryRequest;
import cc.rengu.igas.channel.cpcn.facade.response.CpcnMchntOrderPayQueryResponse;
import cc.rengu.igas.channel.cpcn.facade.response.CpcnMchntOrderPayRefundQueryResponse;
import cc.rengu.igas.channel.cpcn.facade.result.Result;
import cc.rengu.igas.share.common.constant.ShareParamConstant;
import cc.rengu.igas.share.common.constant.ShareServiceConstant;
import cc.rengu.igas.share.common.constant.TransCacheConstant;
import cc.rengu.oltp.service.base.ChannelBaseService;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.*;
import cc.rengu.oltp.service.common.enums.*;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.model.OrderInfo;
import cc.rengu.oltp.service.model.TxnInfo;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.SysParamService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 中金支付商户订单支付退款查询
 * Created by lzl on 2021/4/23 11:08
 */
public class CpcnMchntOrderPayRefundQueryService extends ChannelBaseService {
    @Override
    public Object callPreProc(TxnInfo txnInfo, ChannelCallCfg channelCallCfg, OrderInfo orderInfo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        Header cpcnHeader = new Header();
        cpcnHeader.setInstId(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID));
        cpcnHeader.setChanlId(channelCallCfg.getMsgSrcId());
        cpcnHeader.setSrcSysId(AppParamConstant.SYS_ID);
        cpcnHeader.setBizType(AppParamConstant.DEFAULT_BIZ_TYPE);
        cpcnHeader.setVersion(ShareParamConstant.DUBBO_VSERSION);
        cpcnHeader.setTxnNum(channelCallCfg.getCallChannelTxn());
        cpcnHeader.setTraceNo(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM) + channelCallCfg.getCallIndex());
        cpcnHeader.setTransTime(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_TIME));
        cpcnHeader.setTransDate(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_DATE));
        CpcnMchntOrderPayRefundQueryRequest mchntOrderPayRefundQueryRequest = new CpcnMchntOrderPayRefundQueryRequest();
        mchntOrderPayRefundQueryRequest.setHeader(cpcnHeader);
        /* 机构编码赋值 */
        Predicate<PayOrderInfo> channelFilter = p -> channelCallCfg.getCallChannelId().equals(p.getMsgDstId());
        List<PayOrderInfo> payOrderInfoList = orderInfo.getPayOrderInfoList().stream().filter(channelFilter).collect(Collectors.toList());
        if (null != payOrderInfoList.get(0).getPayerRemark()) {
            JSONObject jsonObject = JSON.parseObject(payOrderInfoList.get(0).getPayerRemark());
            mchntOrderPayRefundQueryRequest.setInstitutionId((String) jsonObject.get(ShareParamConstant.INSTITUTIONID));
        } else {
            SysParamService sysParamService = new SysParamServiceImpl();
            String transMchntNo = (orderInfo.getMchntOrderInfoList().size() > 1) ? orderInfo.getUserOrderInfo().getGroupMchntNo() : orderInfo.getMchntOrderInfoList().get(0).getMchntNo();
            SysParam sysParam = sysParamService.getSysParamInfo(cpcnHeader.getInstId(), "INSTITUTIONID", transMchntNo);
            mchntOrderPayRefundQueryRequest.setInstitutionId((null != sysParam) ? sysParam.getParamValue() : null);
        }
        /* 退款交易流水号 */
        mchntOrderPayRefundQueryRequest.setSerialNumber(orderInfo.getUserOrderInfo().getSysSeqNum());
        rglog.debug("中金支付商户订单支付退款查询请求:<{}>", JSON.toJSONString(mchntOrderPayRefundQueryRequest));
        return mchntOrderPayRefundQueryRequest;
    }

    @Override
    public PayOrderInfo generatePayOrderInfo(ChannelCallCfg channelCallCfg, OrderInfo orderInfo, Object request) throws Exception {
        return null;
    }

    @Override
    public Object callProc(ChannelCallCfg channelCallCfg, Object request) throws Exception {
        CpcnMchntOrderPayRefundQueryRequest mchntOrderPayRefundQueryRequest = (CpcnMchntOrderPayRefundQueryRequest) request;
        /* Step1：调用接口，获取结果 */
        Result<CpcnMchntOrderPayRefundQueryResponse> callResult;
        DubboService dubboService = new DubboServiceImpl();
        if (AppParamConstant.YES.equals(channelCallCfg.getSyncCallFlag())) {
            /* Step1.1：异步调用 */
            int iReturnCode;
            int callTimes = 0 == channelCallCfg.getSyncQueryRepeatNum() ? 1 : channelCallCfg.getSyncQueryRepeatNum();
            int gatTime = channelCallCfg.getSyncQueryRepeatTime();
            int gatType = StringUtil.isEmptyOrNull(channelCallCfg.getSyncQueryGapType()) ? 0 : Integer.parseInt(channelCallCfg.getSyncQueryGapType());
            if (ChannelCallModeEnum.LOCAL.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.1.1：异步应用内调用 */
                Class clasz = Class.forName(ShareServiceConstant.CPCN_SERVICE_INNER_PATH);
                iReturnCode = dubboService.asynCallDubboInnerMethod(clasz, ShareServiceConstant.CPCN_MCHNT_ORDER_PAY_REFUND_QUERY_METHOD, mchntOrderPayRefundQueryRequest, channelCallCfg.getSyncResultServiceName(), callTimes, gatType, gatTime);
            } else if (ChannelCallModeEnum.REMOTE.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.1.2：异步远程调用 */
                iReturnCode = dubboService.asynCallDubboService(ShareServiceConstant.CPCN_SERVICE, ShareServiceConstant.CPCN_MCHNT_ORDER_PAY_REFUND_QUERY_METHOD, mchntOrderPayRefundQueryRequest, channelCallCfg.getSyncResultServiceName(), callTimes, gatType, gatTime);
            } else {
                rglog.error("不支持的通道服务调用方式:{}，交易拒绝!", channelCallCfg.getChannelCallMode());
                throw new BizException(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR);
            }
            if (0 == iReturnCode) {
                return new BizResponse<>(OltpRpcdEnum.TRANS_SUCCESS.getRespCode(), OltpRpcdEnum.TRANS_SUCCESS.getRespDesc());
            } else {
                return new BizResponse<>(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
            }
        } else {
            /* Step1.2：同步调用 */
            if (ChannelCallModeEnum.LOCAL.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.2.1：同步应用内调用 */
                Class clasz = Class.forName(ShareServiceConstant.CPCN_SERVICE_INNER_PATH);
                callResult = (Result<CpcnMchntOrderPayRefundQueryResponse>) dubboService.callDubboInnerMethod(clasz, ShareServiceConstant.CPCN_MCHNT_ORDER_PAY_REFUND_QUERY_METHOD, mchntOrderPayRefundQueryRequest);
            } else if (ChannelCallModeEnum.REMOTE.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.2.2：同步远程调用 */
                callResult = (Result<CpcnMchntOrderPayRefundQueryResponse>) dubboService.callDubboService(ShareServiceConstant.CPCN_SERVICE, ShareServiceConstant.CPCN_MCHNT_ORDER_PAY_REFUND_QUERY_METHOD, mchntOrderPayRefundQueryRequest);
            } else {
                rglog.error("不支持的通道服务调用方式:{}，交易拒绝!", channelCallCfg.getChannelCallMode());
                throw new BizException(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR);
            }
        }
        return callResult;
    }

    @Override
    public Object querySyncCallResult(PayOrderInfo payOrderInfo, Object request) {
        return null;
    }

    @Override
    public OrderInfo callResultOrderProc(OrderInfo orderInfo, String payOrderIndex, TransStatusEnum transStatusEnum, Object response) {
        OrderInfo updateOrderInfo = new OrderInfo();
        Result<CpcnMchntOrderPayRefundQueryResponse> callResult = (Result<CpcnMchntOrderPayRefundQueryResponse>) response;
        Optional<PayOrderInfo> payOrderInfoOpt = orderInfo.getPayOrderInfoList().stream().filter(item -> item.getDstCallIndex().equals(payOrderIndex)).findFirst();
        if (payOrderInfoOpt.isPresent() && null != callResult && null != callResult.getResult()) {
            UserOrderInfo userOrderInfo = orderInfo.getUserOrderInfo();
            List<MchntOrderInfo> mchntOrderInfoList = orderInfo.getMchntOrderInfoList();
            PayOrderInfo payOrderInfo = payOrderInfoOpt.get();
            CpcnMchntOrderPayRefundQueryResponse cpcnMchntOrderPayRefundQueryResponse = callResult.getResult();
            if (TransStatusEnum.TRANS_SUCC.equals(transStatusEnum)) {
                if ("20".equals(cpcnMchntOrderPayRefundQueryResponse.getStatus())) {
                    /* 更新退款用户订单信息 */
                    userOrderInfo.setOrderStatus(OrderStatusEnum.FINISH.getStatus());
                    userOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
                    userOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
                    userOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
                    /* 更新退款商户订单信息 */
                    for (MchntOrderInfo mchntOrderInfo : mchntOrderInfoList) {
                        mchntOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
                        mchntOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
                        mchntOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
                    }
                    /* 更新退款支付订单信息 */
                    payOrderInfo.setRespCode(cpcnMchntOrderPayRefundQueryResponse.getRespCode());
                    payOrderInfo.setRespDesc(cpcnMchntOrderPayRefundQueryResponse.getRespDesc());
                    payOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
                    payOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
                    payOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
                    List<PayOrderInfo> payOrderInfoList = new ArrayList<>();
                    payOrderInfoList.add(payOrderInfo);
                    updateOrderInfo.setUserOrderInfo(userOrderInfo);
                    updateOrderInfo.setMchntOrderInfoList(mchntOrderInfoList);
                    updateOrderInfo.setPayOrderInfoList(payOrderInfoList);
                }
            } else {
                /* 更新当前用户订单信息 */
                userOrderInfo.setOrderStatus(OrderStatusEnum.FINISH.getStatus());
                userOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
                userOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
                userOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
                /* 更新当前商户订单信息 */
                for (MchntOrderInfo mchntOrderInfo : mchntOrderInfoList) {
                    mchntOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
                    mchntOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
                    mchntOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
                }
                /* 更新当前支付订单信息 */
                payOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
                payOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
                payOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
                List<PayOrderInfo> payOrderInfoList = new ArrayList<>();
                payOrderInfoList.add(payOrderInfo);
                updateOrderInfo.setUserOrderInfo(userOrderInfo);
                updateOrderInfo.setMchntOrderInfoList(mchntOrderInfoList);
                updateOrderInfo.setPayOrderInfoList(payOrderInfoList);
            }
        }
        return updateOrderInfo;
    }
}
